import Vue from 'vue';
import { Toast, Dialog } from 'vant'
import router from '../router'
import SETAPI from '../api/settings.js'
Vue.use(Toast);
Vue.use(Dialog);
import i18n from '../lan'

//显示loading
const loadingShow = function() {
    Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: i18n.t('Loading')
    })
}
export default {
    loadingShow,
    //隐藏loading
    toastHide: () => {
        Toast.clear();
    },
    //显示提示
    tipsShow: (txt) => {
        Toast({
            message: i18n.t(txt),
            position: 'bottom'
        });
    },
    //重新登录
    loginAgain: () => {
        Dialog.alert({
            title: i18n.t('Tip'),
            message: i18n.t('LoginExpired'),
            confirmButtonText: i18n.t('OK')
        }).then(() => {
            router.push({ path: '/' });
        });
    },
    //弹出框并跳转
    popAndJump: (txt, pathUrl) => {
        Dialog.alert({
            title: i18n.t('Tip'),
            message: i18n.t(txt),
            confirmButtonText: i18n.t('OK')
        }).then(() => {
            router.push({ path: pathUrl });
        });
    },
    //设置成功
    toastSuccess: () => {
        Toast.success(i18n.t('SetSuccess'));
    },
    //设置失败
    toastFail: () => {
        Toast.fail(i18n.t("SetFaild"));
    },
    //保留2位小数
    fixedTwo: (data, min, max) => {
        let regs = /^[0-9]+\.?[0-9]{0,2}$/;
        let valid;
        if (data >= Number(min) && data <= Number(max)) {
            valid = regs.test(Math.abs(data));
        } else {
            valid = false;
        }
        return valid;
    },
    //保留1位小数
    fixedOne: (data, min, max) => {
        let regs = /^[0-9]+([.][0-9]{1}){0,1}$/;
        let valid;
        if (data >= Number(min) && data <= Number(max)) {
            valid = regs.test(Math.abs(data));
        } else {
            valid = false;
        }
        return valid;
    },
    //设置4位正整数
    fixedFourNum: (data) => {
        let regs = /^[0-9][0-9][0-9][0-9]$/;
        return regs.test(data);
    },
    //设置50的倍数
    fixedfifthNum: (data, min, max) => {
        let regs = /[-+]?\b(?:\d*[50])?0\b/;
        let valid;
        if (data >= Number(min) && data <= Number(max)) {
            valid = regs.test(data);
        } else {
            valid = false;
        }
        return valid;
    },
    //设置20的倍数
    fixedtwentyNum: (data, min, max) => {
        let regs = /^\d*[02468]+0$/;
        let valid;
        if (data >= Number(min) && data <= Number(max)) {
            valid = regs.test(data);
        } else {
            valid = false;
        }
        return valid;
    },
    //保留3位小数
    fixedThree: (data, min, max) => {
        let regs = /^-?\d+(\.\d{1,3})?$/;
        let valid;
        if (data >= Number(min) && data <= Number(max)) {
            valid = regs.test(data);
        } else {
            valid = false;
        }
        return valid;
    },
    //保留4位小数
    fixedFour: (data, min, max) => {
        let regs = /^-?\d+(\.\d{1,4})?$/;
        let valid;
        if (data >= Number(min) && data <= Number(max)) {
            valid = regs.test(data);
        } else {
            valid = false;
        }
        return valid;
    },
    //设置IP地址
    fixedIPAddress: (data) => {
        let regs = /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/;
        return regs.test(data);
    },
    //设置Subnet mask
    fixedSubnetmask: (data) => {
        let regs = /^(254|252|248|240|224|192|128|0)\.0\.0\.0$|^(255\.(254|252|248|240|224|192|128|0)\.0\.0)$|^(255\.255\.(254|252|248|240|224|192|128|0)\.0)$|^(255\.255\.255\.(254|252|248|240|224|192|128|0))$/;
        return regs.test(data);
    },
    //设置DefaultGateway
    fixedDefaultGateway: (data) => {
        let regs = /^\d+.\d+.\d+.\d+$/;
        return regs.test(data);
    },
    //设置密码回显
    showPwd: (data) => {
        let pwd = data.toString();
        let pwdStr = pwd.padStart(4, '0');
        return pwdStr;
    },
    //js乘法计算
    mulFunction: (arg1, arg2) => {
        let m = 0;
        let s1 = arg1.toString();
        let s2 = arg2.toString();
        try { m += s1.split(".")[1].length } catch (e) {}
        try { m += s2.split(".")[1].length } catch (e) {}
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },
    //远程设置(非透传)
    async setData(optType, formData) {
        loadingShow();
        let parmas = formData;
        parmas.optType = optType;
        parmas.sn = localStorage.getItem('wifiSN');
        parmas.tokenId = localStorage.getItem('tokenId');
        let data = await SETAPI.setInvMachine(localStorage.getItem('domain'), parmas);
        if (data.success) {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //本地设置(非透传)
    async bdSetData(optType, formData) {
        loadingShow();
        let parmas = formData;
        parmas.optType = optType;
        parmas.pwd = sessionStorage.getItem('bdPwd');
        let data = await SETAPI.LocalIn(parmas);
        let newdata = data.substring(0, 1);
        if (newdata == "Y") {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //数据转换 flag=1(Uint) flag=0(Int)
    bit16: (flag, value) => {
        if (flag == 1) {
            return value;
        } else if (flag == 0) {
            if (value < 32768) {
                return value;
            } else {
                return value - 65536;
            }
        }
    },
    bit32: (flag, value1, value2) => {
        if (flag == 1) {
            return value1 + value2 * 65536;
        } else if (flag == 0) {
            if (value2 < 32768) {
                return value1 + value2 * 65536;
            } else if (value2 > 32768) {
                return value1 + value2 * 65536 - 4294967296;
            }
        }
    },
    bit8low: (flag, value) => {
        let num = value % 256;
        if (flag == 1) {
            return num;
        } else if (flag == 0) {
            if (num < 128) {
                return num;
            } else {
                return num - 256;
            }
        }
    },
    bit8high: (flag, value) => {
        let num = parseInt(value / 256);
        if (flag == 1) {
            return num;
        } else if (flag == 0) {
            if (num < 128) {
                return num;
            } else {
                return num - 256;
            }
        }
    },
    //远程设置Date Time(透传)
    async setDateTime(Data) {
        loadingShow();
        let parmas = {
            'optType': 'setRTC',
            'sn': localStorage.getItem('wifiSN'),
            'tokenId': localStorage.getItem('tokenId'),
            'YMDHMS': Data
        };
        let data = await SETAPI.setInvMachinePT(localStorage.getItem('domain'), parmas);
        if (data.success) {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //远程设置IP(透传)
    async setIP(IPData, GWData, SUData) {
        loadingShow();
        let parmas = {
            'optType': 'setNet',
            'sn': localStorage.getItem('wifiSN'),
            'tokenId': localStorage.getItem('tokenId'),
            'IP': IPData,
            'GW': GWData,
            'SU': SUData
        };
        let data = await SETAPI.setInvMachinePT(localStorage.getItem('domain'), parmas);
        if (data.success) {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //远程设置(透传)
    async setDataPT(num, Data) {
        loadingShow();
        let parmas = {
            'optType': 'setReg',
            'num': num,
            'sn': localStorage.getItem('wifiSN'),
            'tokenId': localStorage.getItem('tokenId'),
            'Data': JSON.stringify(Data)
        };
        let data = await SETAPI.setInvMachinePT(localStorage.getItem('domain'), parmas);
        if (data.success) {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //远程设置(充电桩))
    async setDataPT(num, Data) {
        loadingShow();
        let parmas = {
            'optType': 'setReg',
            'num': num,
            'sn': localStorage.getItem('pileSn'),
            'tokenId': localStorage.getItem('tokenId'),
            'Data': JSON.stringify(Data)
        };
        let data = await SETAPI.setInvMachinePT(localStorage.getItem('domain'), parmas);
        if (data.success) {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //本地设置Date Time(透传)
    async bdSetDateTime(Datas) {
        loadingShow();
        let parmas = {
            'optType': 'setRTC',
            'pwd': sessionStorage.getItem('bdPwd'),
            'Data': JSON.stringify({ 'YMDHMS': Datas })
        };
        let data = await SETAPI.LocalIn(parmas);
        let newdata = data.substring(0, 1);
        if (newdata == "Y") {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //本地设置IP(透传)
    async bdSetIP(IPData, GWData, SUData) {
        loadingShow();
        let parmas = {
            'optType': 'setNet',
            'pwd': sessionStorage.getItem('bdPwd'),
            'Data': `{IP:"${IPData[0]},${IPData[1]},${IPData[2]},${IPData[3]}",GW:"${GWData[0]},${GWData[1]},${GWData[2]},${GWData[3]}",SU:"${SUData[0]},${SUData[1]},${SUData[2]},${SUData[3]}"}`
        };
        let data = await SETAPI.LocalIn(parmas);
        let newdata = data.substring(0, 1);
        if (newdata == "Y") {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //本地设置(透传)
    async bdSetDataPT(num, Data) {
        loadingShow();
        let parmas = {
            'optType': 'setReg',
            'pwd': sessionStorage.getItem('bdPwd'),
            'data': JSON.stringify({ 'num': num, 'Data': Data })
        };
        let data = await SETAPI.LocalIn(parmas);
        let newdata = data.substring(0, 1);
        if (newdata == "Y") {
            Toast.success(i18n.t('SetSuccess'));
        } else {
            Toast.fail(i18n.t('SetFaild'));
        }
    },
    //电站流动图(非充电桩)
    siteFlowChar: (feedin, grid, pv, battery, loadPower, meter) => {
        //初始化流动图
        let [Z1, Z2, F2, Z3, F3, Z4, F4, Z5, F5] = [false, false, false, false, false, false, false, false, false];
        //PV
        if (pv > 0) {
            Z1 = true;
        }
        //battery
        if (battery > 0 && grid != 0) {
            F2 = true;
        } else if (battery < 0) {
            Z2 = true;
        }
        //逆变器(gridpower)和并网功率(feedinpower)
        if (!meter) {
            if (grid > 0) {
                Z3 = true;
            } else if (grid < 0) {
                F3 = true;
            }
        } else {
            if (feedin > 0) {
                Z3 = true;
            } else if (feedin < 0) {
                F3 = true;
            }
        }
        //load
        if (loadPower > 0) {
            Z4 = true;
        }
        if (loadPower < 0) {
            //同时逆变器为正，电网为正的话就流向电网；逆变器为负，电网为负的话就流向逆变器；逆变器为负，电网为正的话就两个都流
            if (grid > 0 && feedin > 0) {
                F5 = true;
            }
            if (grid < 0 && feedin < 0) {
                F4 = true;
            }
            if (grid < 0 && feedin > 0) {
                F5 = true;
                F4 = true;
            }
        }
        if (feedin < 0) {
            Z5 = true;
        }
        return [Z1, Z2, F2, Z3, F3, Z4, F4, Z5, F5];
    },
    //逆变器流动图(非充电桩)
    MyFlowChar: (feedin, grid, pv, battery, loadPower, meter) => {
        //初始化流动图
        let [Z1, Z2, F2, Z3, F3, Z4, F4, Z5, F5] = [false, false, false, false, false, false, false, false, false];
        //PV
        if (pv > 0) {
            Z1 = true;
        }
        //battery
        if (battery > 0 && grid != 0) {
            F2 = true;
        } else if (battery < 0) {
            Z2 = true;
        }
        //逆变器(gridpower)和并网功率(feedinpower)
        if (grid > 0 && feedin > 0) {
            Z3 = true;
        } else if (grid < 0 && feedin < 0) {
            F3 = true;
        }
        //当没有电表时：逆变器功率为正，流动同时从逆变器向电网和负载；逆变器功率为负，流动从电网到逆变器，负载没有；逆变器功率为0，没有流动
        if (!meter) {
            if (grid > 0) {
                Z3 = true;
                Z4 = true;
            } else if (grid < 0) {
                F3 = true;
            }
        }
        //load
        if (loadPower > 0 && grid > 0) {
            Z4 = true;
        }
        if (loadPower < 0 && grid < 0) {
            F4 = true;
        }
        if (loadPower > 0 && feedin < 0) {
            Z5 = true;
        }
        if (loadPower < 0 && feedin > 0) {
            F5 = true;
        }
        return [Z1, Z2, F2, Z3, F3, Z4, F4, Z5, F5];
    },
    //电站流动图(充电桩)
    siteEVchar: (feedin, grid, pv, battery, loadPower, meter, charge) => {
        //初始化流动图
        let [pvtoinv, battoinv, invtobat, invtofeed, feedtoinv, invtoload, loadtoinv, invtocharge, chargetoinv, feedtoload, loadtofeed, chargetoload, loadtocharge] = [false, false, false, false, false, false, false, false, false, false, false, false, false];
        //PV
        if (pv > 0) {
            pvtoinv = true;
        }
        //battery
        if (battery > 0 && grid != 0) {
            invtobat = true;
        } else if (battery < 0) {
            battoinv = true;
        }
        //逆变器(gridpower)和并网功率(feedinpower)
        if (!meter) {
            if (grid > 0) {
                invtofeed = true;
            } else if (grid < 0) {
                feedtoinv = true;
            }
        } else {
            if (feedin > 0) {
                invtofeed = true;
            } else if (feedin < 0) {
                feedtoinv = true;
            }
        }
        //load
        if (loadPower > 0) {
            invtoload = true;
        }
        if (loadPower < 0) {
            //同时逆变器为正，电网为正的话就流向电网；逆变器为负，电网为负的话就流向逆变器；逆变器为负，电网为正的话就两个都流
            if (grid > 0 && feedin > 0) {
                loadtofeed = true;
            }
            if (grid < 0 && feedin < 0) {
                loadtoinv = true;
            }
            if (grid < 0 && feedin > 0) {
                loadtofeed = true;
                loadtoinv = true;
            }
        }
        if (feedin < 0) {
            feedtoload = true;
        }
        //充电桩
        if (grid > 0 && charge > 0) {
            invtocharge = true;
        }
        if (grid < 0 && charge < 0) {
            chargetoinv = true;
        }
        if (charge > 0 && loadPower < 0) {
            loadtocharge = true;
        }
        if (charge < 0 && loadPower > 0) {
            chargetoload = true;
        }
        return [pvtoinv, battoinv, invtobat, invtofeed, feedtoinv, invtoload, loadtoinv, invtocharge, chargetoinv, feedtoload, loadtofeed, chargetoload, loadtocharge];
    },
    //充电桩流动图
    EVchar: (inverter, feedin, loadPower, oterload, charge) => {
        //初始化流动图
        let [invtoload, loadtoinv, feedtoload, loadtofeed, loadtootherload, otherloadtoload, loadtocharge, chargetoload] = [false, false, false, false, false, false, false, false];
        //load
        if (loadPower > 0) {
            invtoload = true;
        }
        if (loadPower < 0) {
            loadtoinv = true;
        }
        if (feedin < 0) {
            feedtoload = true;
        }
        //充电桩
        if (charge > 0 && loadPower < 0) {
            loadtocharge = true;
        }
        if (charge < 0 && loadPower > 0) {
            chargetoload = true;
        }
        //other Load
        if (oterload > 0 && loadPower < 0) {
            loadtootherload = true;
        }
        if (oterload < 0 && loadPower > 0) {
            otherloadtoload = true;
        }
        return [invtoload, loadtoinv, feedtoload, loadtofeed, loadtootherload, otherloadtoload, loadtocharge, chargetoload];
    }
}